package com.sibu.yx.promotion.admin.web.support.filter;


import com.doubo.json.util.JsonUtil;
import com.sibu.yx.promotion.common.enums.ErrorCodeEnum;
import com.sibu.yx.promotion.common.manage.ResponseManage;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @author     ：yuwenbo
 * @date       ：Created in 2019/4/15 15:56
 * @description：本地拦戴url
 */
public class CustomTokenFilter extends AccessControlFilter {

    /**
     * 验证是否有登陆信息
     * @param servletRequest
     * @param servletResponse
     * @param o
     * @return
     * @throws Exception
     * 直接调用登陆token
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
//        HttpServletRequest request=(HttpServletRequest) servletRequest;
//        String token=request.getHeader("MALL_TOKEN");
//        String uid=request.getHeader("UID");
//        if(StringUtil.isNull(token)||StringUtil.isNull(uid)){
//            return false;
//        }
//        UidToken tokenUidSubject=new UidToken();
//        tokenUidSubject.setToken(token);
//        tokenUidSubject.setUid(uid);
//        Subject subject= SecurityUtils.getSubject();
//        subject.login(tokenUidSubject);
//        //user:udpate 可以对比到user:*,user,
//        Boolean isPermitted=subject.isPermittedAll("user:update","+7");
//        if(!isPermitted){
//            return isPermitted;
//        }
//        return subject.isAuthenticated();
        Subject subject = getSubject(servletRequest, servletResponse);
        return subject.isAuthenticated();
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        servletResponse.setContentType("application/json;charset=UTF-8");
        servletResponse.setCharacterEncoding("utf-8");
        servletResponse.getWriter().write(JsonUtil.toJson(ResponseManage.fail(ErrorCodeEnum.SESSION_TIMEOUT)));
        return false;
    }

}
